package com.star.common.email.service;

import com.star.common.email.config.EmailProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

/**
 * email service类
 *
 * @author zhouhengzhe
 * @version 1.0
 * @date 2023/6/16 14:53
 */
@Slf4j
public class StarEmailService {
    private final JavaMailSender javaMailSender;
    
    private final EmailProperties emailProperties;

    public StarEmailService(JavaMailSender javaMailSender,
                            EmailProperties emailProperties) {
        this.javaMailSender = javaMailSender;
        this.emailProperties = emailProperties;
    }

    /**
     * 发送邮件（可以单个，可以多个人）
     *
     * @param from    发送者
     * @param to      收件人
     * @param cc      抄送人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String from, List<String> to, String cc, String subject, String content) {
        try {
            //简单邮件
            SimpleMailMessage simpleMessage = new SimpleMailMessage();
            simpleMessage.setFrom(aliasFrom(from));
            simpleMessage.setTo(to.toArray(new String[0]));
            simpleMessage.setCc(cc);
            simpleMessage.setSubject(subject);
            simpleMessage.setText(content);
            //发送邮件
            javaMailSender.send(simpleMessage);
        } catch (Exception e) {
            log.error("发送失败", e);
            throw new RuntimeException("发送单人邮件失败", e);
        }
    }
    /**
     * 可以不需要填写抄送方，只需要填null
     *
     * @param from    发送者,别名
     * @param to      收件人
     * @param cc      抄送人
     * @param subject 邮件主题
     * @param content 邮件内容
     */
    public void sendSimpleMail(String from, String to, String cc, String subject, String content) {
        //简单邮件
        SimpleMailMessage simpleMessage = new SimpleMailMessage();
        simpleMessage.setFrom(aliasFrom(from));
        simpleMessage.setTo(to);
        if (StringUtils.isNotBlank(cc)) {
            simpleMessage.setCc(cc);
        }
        simpleMessage.setSubject(subject);
        simpleMessage.setText(content);
        //发送邮件
        javaMailSender.send(simpleMessage);
    }
    /**
     * 发送带附件的邮件
     *
     * @param from    发送者
     * @param to      收件人
     * @param cc      抄送人
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param file    发送的文件
     */
    public void sendAttachFileMail(String from, String to, String cc, String subject, String content, File file) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(aliasFrom(from));
            helper.setTo(to);
            helper.setCc(cc);
            helper.setSubject(subject);
            helper.setText(content);
            helper.addAttachment(file.getName(), file);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            log.error("发送失败", e);
            throw new RuntimeException("发送带附件的邮件失败", e);
        }
    }

    /**
     * 发送带图片的邮件
     *
     * @param from    发送者
     * @param to      收件人
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param srcPath 图片资源路径
     * @param resIds  资源id
     */
    public void sendMailWithImg(String from, String to, String subject, String content, String[] srcPath, String[] resIds) {
        if (srcPath.length != resIds.length) {
            throw new RuntimeException("图片为空或者资源ID为空");
        }
        try {
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(aliasFrom(from));
            helper.setTo(to);
            helper.setSubject(subject);
            //默认false,设置为true表示邮件正文是html格式。
            helper.setText(content, true);
            for (int i = 0; i < srcPath.length; i++) {
                FileSystemResource res = new FileSystemResource(new File(srcPath[i]));
                helper.addInline(resIds[i], res);
            }
            javaMailSender.send(message);
        } catch (MessagingException e) {
            log.error("发送失败", e);
            throw new RuntimeException("发送带附件的邮件失败", e);
        }
    }


    /**
     * 设置别名
     *
     * @param from 发送方，别名
     */
    private String aliasFrom(String from) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(from)) {
            sb.append(from).append('<').append(emailProperties.getUsername()).append('>');
        } else {
            sb.append(emailProperties.getUsername());
        }
        return sb.toString();
    }
}
